#include <iostream>
#include <stdio.h>
#include <cerrno>
#include <cassert>
#include <string>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

using namespace std;

int main()
{
    //1. 让进程看到同一份资源
    //1.1创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if(n == -1)
    {
        cout << "pipe,errno : " << errno << strerror(errno) << endl;
        exit(1);
    }
    //2. 创建子进程
    pid_t id = fork();
    assert(id >= 0);
    (void)id;
    //子进程向父进程通信
    int cnt = 0;
    if(id == 0)//子进程
    {
        //3.子进程写数据，关闭读端
        close(pipefd[0]);
        string str = "hello,我是子进程";
        char buff[1024] = {0};
        while(true)
        {
            snprintf(buff,sizeof(buff),"%s,%d %d",str.c_str(),getpid(),cnt++);
            write(pipefd[1],buff,strlen(buff));
            sleep(1);
        }
        exit(0);
    }
    //父进程
    //3.父进程，读数据
    close(pipefd[1]);
    char buff[1024] = {0};
    while(true)
    {
        int n = read(pipefd[0],buff,sizeof(buff)-1);
        if(n > 0)
        {
            buff[n] = '\0';
            cout <<"我是父进程，child send me :" << buff << endl;
        }
        else if(n == 0)
        {
            cout << "写端关闭，我读到了0个字节" << endl;
            break;
        }
        else
        {
            cout << "pipe,errno : " << errno << strerror(errno) << endl;
            exit(1);
        }
        sleep(2);
        break;
    }

    close(pipefd[0]);
    int status = 0;
    waitpid(id,&status,0);
    cout << "child singal : " << (status & 0x7F) << endl;

    return 0;
}